package cqie.personal.frame.service.impl;


import cqie.personal.frame.exception.ValidationFailException;
import cqie.personal.frame.service.UploadDownloadService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class UploadDownloadServiceImpl implements UploadDownloadService {
    private static final String FILE_UPLOAD_PATH = "D:\\工作文件\\我的网站\\vue_test\\static\\img\\";
    private static final String[] whiteList = {"png", "jpg", "jpeg"};

    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_UNCOMMITTED)
    public String upload(MultipartFile files) throws ValidationFailException {
            String originalFilename = files.getOriginalFilename();
            if (originalFilename == null) {
                return null;
            }
            String[] type = originalFilename.split("\\.");
            boolean t = false;
            for (String white : whiteList) {
                if (white.equalsIgnoreCase(type[1])) {
                    t = true;
                    break;
                }
            }
            if (!t) {
                throw new ValidationFailException("不允许上传的格式");
            }
            String fileName = UUID.randomUUID() + "&" + originalFilename;
            try {
                files.transferTo(new File(FILE_UPLOAD_PATH + fileName));
            } catch (IOException e) {
                throw new ValidationFailException("上传失败");
            }
            return "/static/img/"+fileName;
    }

}